package com.leonzx.base.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 梁亮 on 2018/3/28.
 */
@Configuration
@EnableAutoConfiguration
public class DataSourceCreator {
    /**
     * 配置多数据源，缓存起来
     */
    private Map<Object, Object> dsMap = new HashMap<>();

    /**
     * 默认数据源
     *
     * @return
     */
    @Bean(name = "leonlims")
    @ConfigurationProperties(prefix = "spring.datasource.leonlims")
    public DataSource dataSourceLeonlims() {
        DruidDataSource dataSource = new DruidDataSource();
        dsMap.put("leonlims", dataSource);
        return dataSource;
    }

    /**
     * 第二个数据源
     * @return
     */
    @Bean(name = "leonlims1")
    @ConfigurationProperties(prefix = "spring.datasource.leonlims1")
    public DataSource dataSourceLeonlimsLiang() {
        DruidDataSource dataSource = new DruidDataSource();
        dsMap.put("leonlims1", dataSource);
        return dataSource;
    }

    /**
     * 创建动态数据源
     *
     * @return
     */
    @Bean(name = "dataSource")
    @DependsOn({"leonlims", "leonlims1"})
    public DataSource dataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dsMap.get(DataSourceContextHolder.DEFAULT_DS));
        //将数据源缓存map放入动态数据源中
        dynamicDataSource.setTargetDataSources(dsMap);
        return dynamicDataSource;
    }
}
